import { ConfApi } from "./conf-api";
import { RuleApi } from "./rule-api";
import { RuleInfo, GlobalConfig, PriceRes, RuleType } from "../modules";
import { Sina } from "../api/Sina";
import { Notification } from 'electron'


export class Task {

    constructor(conf: ConfApi, rule: RuleApi, api: Sina ) {
        this.confHandler = conf;
        this.ruleHandler = rule;
        this.searchHandler = api;
    }

    private confHandler: ConfApi;
    private ruleHandler: RuleApi;
    private searchHandler: Sina;
    private intervalHandler: any;

    private rules: RuleInfo[];
    private conf: GlobalConfig;

    /**
     * task run.
     */
    run() {
        console.log("task started! with conf:");
        console.log(JSON.stringify(this.conf));
        let _this = this;
        if (this.intervalHandler) {
            clearInterval(this.intervalHandler);
        }
        this.intervalHandler = setInterval(() => {
            // interval
            this.searchHandler.intervalSearch(this.stockItems(), (info: Map<string, PriceRes>) => {

                _this.ruleCheck(info);
            });
        }, this.conf.intervalMs);
    }

    ruleCheck(res: Map<string, PriceRes>) {
        for (let i=0; i<this.rules.length; i++) {
            let singleRule = this.rules[i];
            if (singleRule && res[singleRule.sharesCode]) {
                let price: PriceRes = res[singleRule.sharesCode];
                let ruleType = singleRule.ruleType;
                let ruleValue: number = singleRule.ruleValue;

                let isUp = price.currentPrice > price.startPrice;
                let diff = Math.abs(price.currentPrice - price.startPrice);
                let percentent = (diff/price.startPrice) * 100;
                let flag:boolean = false;
                console.log(ruleType);
                switch(ruleType){
                    case "DF": // 跌幅
                        console.log("****DF");
                        if (!isUp) {
                            if (percentent >= ruleValue) {
                                flag = true;
                            }
                        }
                        break;
                    case "ZF": // 涨幅
                        console.log("****DF");
                        if (isUp) {
                            if (percentent >= ruleValue) {
                                flag =  true;
                            }
                        }
                        break;
                    case "JGZ": // 价格涨至
                        if (isUp) {
                            if (price.currentPrice >= ruleValue) {
                                flag = true;
                            }
                        }
                        break;
                    case "JGD": // 价格跌至
                        if (!isUp) {
                            if (price.currentPrice <= ruleValue) {
                                flag = true;
                            }
                        }
                        break;
                    default:
                        break;
                }
                if (flag) {
                    this.doNotification(singleRule, price);
                }

            }
        }
    }

    /**
     * task initialize.
     */
    load() {
        this.rules = this.ruleHandler.getAll();
        this.conf = this.confHandler.getAll();
        this.run();
    }
    
    doNotification(ruleInfo: RuleInfo, price: PriceRes) {
        let ruleType = ruleInfo.ruleType;
        let ruleTypeText = "";
        switch(ruleType) {
            case "DF":
                ruleTypeText = `跌幅>=`;
                break;
            case "ZF":
                ruleTypeText = `涨幅>=`;
                break;
            case "JGZ":
                ruleTypeText = `价格>=`;
                break;
            case "JGD":
                ruleTypeText = `价格<=`;
                break;
            default:
                break;
        }

        let msg = this.generateByTemplate(this.conf.notificationTemplate, ruleTypeText, ruleInfo.ruleValue, price);
        let notification = new Notification({
            title: this.conf.hideNotificationDetail ? '提示' : `${ruleInfo.ruleName}`,
            subtitle: this.conf.hideNotificationDetail ? '您收到一条新提示！！' :`${ruleInfo.sharesName}(${ruleInfo.sharesCode})`,
            body: this.conf.hideNotificationDetail ? '' : msg,
            silent: false,
            timeoutType: 'default',
        });
        notification.show()
    }

    generateByTemplate (template: string, ruleTypeText: string, ruleValue: number, price: PriceRes) {
        template = template.replace(new RegExp("{RULE_TYPE}",'g'), ruleTypeText);
        template = template.replace(new RegExp("{RULE_VALUE}",'g'), ruleValue.toString());
        template = template.replace(new RegExp("{CURRENT_PRICE}",'g'), price.currentPrice.toString());
        return template;
    }
    
    /**
     * build shares code list like ['sh123123', 'sz234234123'].
     */
    private stockItems(): string[] {
        let res: string[] = [];
        for (let i=0; i<this.rules.length; i++) {
            res.push(this.rules[i].sharesCode);
        }
        return res;
    }

}